package com.crm.service.system.impl;

import cn.hutool.core.util.ObjectUtil;
import com.crm.context.BaseContext;
import com.crm.dto.PageResult;
import com.crm.dto.QueryDictTypeDto;
import com.crm.exception.BaseException;
import com.crm.mapper.system.DictDataMapper;
import com.crm.mapper.system.DictTypeMapper;
import com.crm.pojo.Dict;
import com.crm.pojo.DictData;
import com.crm.pojo.User;
import com.crm.service.system.DictDataService;
import com.crm.service.system.DictTypeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * @ClassName DictTypeServiceImpl
 * @Description
 * @Author 19632
 * @Date 2024/10/28 11:34
 * @Version
 **/
@Service
public class DictTypeServiceImpl implements DictTypeService {

    @Autowired
    private DictTypeMapper dictTypeMapper;
    @Autowired
    private DictDataMapper dataMapper;

    @Override
    public Page<Dict> queryAll(QueryDictTypeDto dto) {

        dto.check();
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());

        Map<String, Object> params = dto.getParams();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        LocalDate beginTime = ObjectUtil.isEmpty(params)?null:(LocalDate.parse((String)params.get("beginTime"), formatter));
        LocalDate endTime =ObjectUtil.isEmpty(params)?null:(LocalDate.parse((String)params.get("endTime"), formatter));

        dto.setBeginTime(beginTime);
        dto.setEndTime(endTime);

        Page<Dict>page=dictTypeMapper.page(dto);

        return page;
    }

    @Override
    public void save(Dict dict) {
        Long userId = BaseContext.getCurrentId();
        User user =dictTypeMapper.searchByUserId(userId);
        dict.setCreateBy(user.getName());
        dictTypeMapper.add(dict);
    }

    @Override
    public Dict getById(Integer id) {
        return dictTypeMapper.getById(id);
    }

    @Override
    public void update(Dict dict) {
        Long userId = BaseContext.getCurrentId();
        User user =dictTypeMapper.searchByUserId(userId);
        dict.setUpdateBy(user.getName());
        dictTypeMapper.update(dict);
    }

    @Override
    public void delete(List<Integer> ids) {
        List<Dict>dictList=dictTypeMapper.seachByIds(ids);
        for (Dict dict : dictList) {
            if(dict.getStatus()==1){
                throw new BaseException("在用状态,不可删除!!");
            }
            Integer dictId = dict.getDictId();
            List<DictData>dictDataList=dataMapper.searchByDictId(dictId);
            if(!CollectionUtils.isEmpty(dictDataList)){
                throw new BaseException("已有数据被分配,不可删除!!");
            }
        }
        dictTypeMapper.delete(ids);
    }
}
